package game.client;

import game.client.net.WorldObjectListener;
import game.common.world.Vector;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingGameWorld implements WorldObjectListener{
	private Map<String,JMEObj> objects = new TreeMap<String,JMEObj>();

	private WorldPanel gui;
	
	class JMEObj {
		String name;
		Vector vector;
	}
	
	@Override
	public void objectMoved(String name, Vector newPos) {
		// System.out.println("object moved "+ name);
		JMEObj jmeObj = null;
		if (objects.containsKey(name)){
			jmeObj = objects.get(name);
		} else {
			jmeObj = newObject(name);
			jmeObj.vector = newPos;
			objects.put(name, jmeObj);
			System.out.println("object '" + name + "' created");
		}
		updateObject(jmeObj, newPos);
		// System.out.println("object '" + name + "' updated at " + newPos);
		
		if (gui != null)
			gui.repaint();
	}

	@Override
	public void objectDeleted(String obj) {
		objects.remove(obj);
		System.out.println("object '" + obj + "' deleted");

		if (gui != null)
			gui.repaint();
	}
	
	private JMEObj newObject(String name){
		JMEObj o = new JMEObj();
		o.name = name;
		return o;
	}
	
	private void updateObject(JMEObj obj, Vector newPos){
		obj.vector.copy(newPos);
	}
	
	static class GUI extends JFrame{
		private static final long serialVersionUID = -1554992568335871314L;
		
		public GUI(SwingGameWorld world,String pName) {
			super(pName); 
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			add(world.new WorldPanel(pName));
			pack();
		}
	}
	
	class WorldPanel extends JPanel{
		private static final long serialVersionUID = -4390052998701835025L;
		
		private String playerName;
		
		public WorldPanel(String pName) {
			setPreferredSize(new Dimension(800,600));
			this.playerName = pName;
			setBackground(Color.BLACK);
			gui = this;
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			
			for (JMEObj obj : objects.values()){
				Color oldCol = g.getColor();
				
				if (obj.name.equals(playerName)) 
					g.setColor(Color.WHITE);
				else
					g.setColor(Color.RED);
				
				g.drawRect((int) (obj.vector.getXf() - 10), (int) (obj.vector.getYf() - 10), 20, 20);
				g.drawString(obj.name, (int) obj.vector.getXf() - 10, (int) obj.vector.getYf() - 15);
				g.setColor(oldCol);
			}
		}
	}
}
